package fv;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import java.sql.*;

/**
 * Servlet implementation class login
 */
public class login extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	String username = "";
	String pwdstr = "";
	String sqlstr = "";
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public login() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		username = request.getParameter("username");
		pwdstr = request.getParameter("password");
		sqlstr = "select userpwd from ferdict_user where username = '" + username + "' or emailaddr = '" + username + "'";
		JSONObject json = new JSONObject();
		
		Connection conn = mysqlconn.getConn();
		if (conn != null) {
			try {
				Statement s = conn.createStatement();
				ResultSet rs = s.executeQuery(sqlstr);
				if (rs != null) {
					String pwd = rs.getString(1);
					if (pwd.compareTo(pwdstr) == 0)
						json.put("login", "succeed");
					else
						json.put("login", "failed");
				} else {
					json.put("login", "no user");
				}
				rs.close();
				s.close();
			} catch (Exception e) {
				System.out.println(e.getMessage());
			}
		}
		mysqlconn.closeConn(conn);
		response.setContentType("application/json");
		response.getWriter().write(json.toString());
	}

	/**
	 * @see HttpServlet#doPut(HttpServletRequest, HttpServletResponse)
	 */
	protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
//		request.getSession(false);
		request.getSession().invalidate();
	}

}
